package com.itheima.controller;


import cn.hutool.core.util.RandomUtil;
import com.itheima.pojo.*;

import com.itheima.service.Userservice;
import com.itheima.utils.JwtUtil;
import com.itheima.utils.Md5Util;
import com.itheima.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private Userservice Userservice;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private JavaMailSender javaMailSender;

    @PostMapping("/register")
    public Result findByUserName(@Pattern(regexp = "^\\S{5,16}$") String username,
                                 @Pattern(regexp = "^\\S{5,16}$") String password,
                                 @Pattern(regexp = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$") String email,
                                 @Pattern(regexp = "^\\S{1,8}$") String nickname
    ){
        User u = Userservice.findByUserName(username);
        if(u==null){
            Userservice.register(username,password,email,nickname);
            return Result.success();
        }else{
            return Result.error("用户名已存在");
        }
    }
    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{5,16}$") String username , @Pattern(regexp = "^\\S{5,16}$") String password){
        User loginu = Userservice.findByUserName(username);
        if(loginu==null){
            return Result.error("用户不存在");
        }else{
            if(Md5Util.getMD5String(password).equals(loginu.getPassword())){
                Map<String,Object> claim = new HashMap<>();
                claim.put("id",loginu.getId());
                claim.put("username",loginu.getUsername());
                String token = JwtUtil.genToken(claim);
                ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
                operations.set(token,token,1, TimeUnit.HOURS);
                return  Result.success(token);
            }else{
                return Result.error("密码错误");
            }
        }
    }

    @GetMapping("/userInfo")
    public Result getUserInfo(){
        Map<String, Object> map = ThreadLocalUtil.get();
        String username  = (String) map.get("username");

        User user = Userservice.findByUserName(username);
        return Result.success(user);
    }

    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user){
        Userservice.update(user);
        return Result.success();
    }

    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl){
         Userservice.updateAvatar(avatarUrl);
         return Result.success();
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody @Validated Password password,@RequestHeader("Authorization") String token){
         String oldPwd = password.getOld_pwd();
        String newPwd = password.getNew_pwd();
        String rePwd = password.getRe_pwd();


        if(!StringUtils.hasLength(newPwd) || !StringUtils.hasLength(oldPwd)   ||  !StringUtils.hasLength(rePwd)){
            return Result.error("缺少必要参数");
        }

        Map<String,Object>  map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User loginUser = Userservice.findByUserName(username);
        if(!loginUser.getPassword().equals(Md5Util.getMD5String(oldPwd))){
            return Result.error("原密码输入错误");
        }

        if(loginUser.getPassword().equals(Md5Util.getMD5String(newPwd))){
            return Result.error("新旧密码不能一样");
        }


        if(!newPwd.equals(rePwd)){
            return Result.error("两次密码输入不一样");
        }
        Userservice.updatePassword(newPwd);

        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);
        return Result.success();
    }
    @GetMapping("/getEmailCode")
    public Result getEmailCode(@RequestParam("email")  String email,@RequestParam("username") String username){
        String UserEmail =  Userservice.findEmailByUserName(username);
        if(!Objects.equals(UserEmail,email)){
            return Result.error("邮箱不匹配");
        }
        SimpleMailMessage message = new SimpleMailMessage();
        String code = RandomUtil.randomNumbers(6);
        String context = "【验证码】您的验证码为：" + code + " 。 验证码五分钟内有效，逾期作废.";
        message.setText(context);
        message.setTo(email);
        message.setFrom(email);
        javaMailSender.send(message);
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.set("code",code,5,TimeUnit.MINUTES);
        return Result.success("发送成功");
    }
    @PatchMapping("/forgetPassword")
    public Result forgetPwd(@RequestBody @Validated Password password){
        String newPwd = password.getNew_pwd();
        String rePwd = password.getRe_pwd();
        String username = password.getUsername();
        String code = password.getCode();
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        if(operations.get("code").equals(code)){
            if(!StringUtils.hasLength(newPwd) ||  !StringUtils.hasLength(rePwd)){
                return Result.error("缺少必要参数");
            }
            if(!newPwd.equals(rePwd)){
                return Result.error("两次密码输入不一样");
            }
            Userservice.findByUserName(username);
            Userservice.forgetPassword(newPwd,username);
            return Result.success();
        }else{
            return Result.error("验证码错误");
        }
    }
    @GetMapping("/allUserInfo")
    public Result<PageBean<User>> getAllUserInfo(Integer  pageNum,
                                              Integer  pageSize,
                                              @RequestParam(required = false) String  nickname,
                                              @RequestParam(required = false) String email){
        PageBean<User> pb = Userservice.findAllUser(pageNum,pageSize,nickname,email);
        return Result.success(pb);
    }
    @DeleteMapping("/deleteUser")
    public Result deleteUser(Integer id){
        Userservice.deleteUser(id);
        return Result.success();
    }
}
